<template>
  <div>
    <TopTab v-model="configTab" @changeTabNum="tabNum = $event" />
    <!-- 必须要加key，不然会往浏览器历史堆栈里增加记录，使用key每次变更重新产生虚拟dom和真实dom -->
    <iframe :key="activeUrl" :class="`container ${tabNum}`" :src="activeUrl" frameborder="0"></iframe>
    <BottomTab v-model="configTab" />
  </div>
</template>

<script setup lang="ts">
import TopTab from '@/components/top/TopTab.vue';
import BottomTab from '@/components/bottom/BottomTab.vue';
import { reqHighendConfig } from '@/apis/index';
import { type HighendConfig, type ClientKey, type Tab, type TabNum } from '@/types/home.d';
import { errorReport, setTitle, transformKeys } from '@/utils/tools';

// 当前参数client
const clientKey = window.getParam('client') as ClientKey;

// 配置数组
const configTab = ref<Tab[]>([]);
// 当前选中的url
const activeUrl = computed(() => {
  let result = '';
  // 使用find降低时间复杂度
  configTab.value.find(item => {
    if (!item.active) {
      return false;
    }
    return item.subTab.find(secondItem => {
      if (!secondItem.active) {
        return false;
      }
      if (!Array.isArray(secondItem.subTab)) {
        result = secondItem.jumpUrl as string;
        return true;
      }
      return secondItem.subTab.find(thirdItem => {
        if (thirdItem.active) {
          result = thirdItem.jumpUrl as string;
          return true;
        }
      });
    });
  });
  console.log(result)
  return result;
});

const tabNum = computed<TabNum>(() => {
  const activeTab = configTab.value.find(item => item.active);
  if (activeTab?.subTab.length === 1) {
    return 'not-tab';
  } else if (!activeTab?.subTab.find(i => i.active && i.subTab)) {
    return 'one-tab';
  } else {
    return 'two-tab';
  }
});
// 初始化选中tab
const initActive = (configSubTab: Tab[]) => {
  configSubTab[0].active = true;
  configSubTab.forEach(item => {
    item.subTab.forEach((i, index) => {
      if (index === 0) {
        i.active = true;
      }
      // 为每一个三级页的第一项定为默认选中
      if (Array.isArray(i.subTab)) {
        i.subTab[0].active = true;
      }
    });
  });
  return configSubTab;
};

const getHighConfig = () => {
  reqHighendConfig({ key: 'highendClient' })
    .then(res => {
      const configItem = res.highendClient.find(item => item.key === clientKey);
      const config = transformKeys(JSON.parse(configItem?.config || '')) as HighendConfig;
      setTitle(config.appName);
      configTab.value = initActive(config.subTab);
    })
    .catch(err => {
      console.log(err);
      errorReport({
        name: `getHighConfig方法报错，clientKey为${clientKey}。${err.name}`,
        message: err.message,
        stack: err.stack
      });
    });
};
onMounted(() => {
  getHighConfig();
});
</script>

<style scoped lang="less">
.container {
  width: 100vw;
  &.not-tab {
    height: calc(100vh - 63px);
  }
  &.one-tab {
    height: calc(100vh - 111px);
  }
  &.two-tab {
    height: calc(100vh - 151px);
  }
}
</style>
